<template>
	<view class="content">
		<view class="header">
			<image lazy-load class="closeIcon" @click="to"
				src="http://cdn.yic3.cn/lawyer/mp-xhs/guide/closeIconWhite.png" mode=""></image>
			<image lazy-load class="textImg" src="http://cdn.yic3.cn/lawyer/mp-xhs/guide/icon19.png" mode="widthFix">
			</image>
		</view>
		<view class="vip_title">
			<view class="item" v-if="goodList[0]">
				<view class="item_1" :class="shows==index?'item_1_1':''" @click="change(index)"
					v-for="(item,index) in goodList" :key="index">
					<view class="title">{{item.name}}</view>
					<view class="money" style="align-items: baseline;"><text
							style="font-size: 28rpx;">￥</text>{{item.showPrice}}</view>
					<view class="oldmoney">
						<text>￥</text>{{item.originPrice}}
					</view>
					<image v-if="shows==index &&  item.tipsUrl" src="http://cdn.yic3.cn/lawyer/mp-xhs/guide/icon20.png"
						mode="widthFix"></image>
				</view>
			</view>
			<!-- <view class="buttom">
				<view class="bottom" @click="gonext()">
					立即开通
				</view>
			</view> -->
		</view>
		<view class="payBtnBox">
			<block v-if="couponShow3">
				<u-checkbox-group size="12" activeColor="#BD7518" @change="couponChange" v-model="checkValue">
					<view class="coupon">
						<view class="couponText">
							<image class="imgCou" src="https://cdn.yic3.cn/lawyer/mp-xhs/guide/coupon2.png"
								mode="widthFix">
							</image>
							<p>优惠提醒：你有<text>80元</text> 优惠券，即将失效<u-count-down style="color: #ff0000;" v-if="couponShow3"
									:time="24 * 60 * 60 * 1000" format="HH:mm:ss" @change="timeChange">
									<text>{{timeData.hours>9?timeData.hours:'0'+timeData.hours}}:{{timeData.minutes>9?timeData.minutes:'0'+timeData.minutes}}:{{timeData.seconds>9?timeData.seconds:'0'+timeData.seconds }}</text>
								</u-count-down></p>
						</view>
						<u-checkbox shape="circle">
						</u-checkbox>
					</view>
				</u-checkbox-group>
			</block>
			<view class="bottom" @click="gonext()" v-if="goodList[shows]">
				<text>￥</text>
				<text
					v-if="!countDown">{{couponIndex==shows && checkValue.length && showOrigin?goodList[shows].price - 80:goodList[shows].price}}</text>
				<u-count-to v-else :duration="800" :useEasing="false" bold color="#411E0E"
					:startVal="goodList[shows].price" :endVal="goodList[shows].price - 80"></u-count-to>
				<text style="margin-left: 20rpx;">立即开通{{goodList[shows].name}}</text>
			</view>
		</view>
		<view class="item_3">
			<image lazy-load src="https://cdn.yic3.cn/lawyer/images/vipBottomBg.png" mode="widthFix"></image>
		</view>
		<conponPop @openCoupon="openCoupon" @editOriginPrice="editOriginPrice" v-if="coupopShow"></conponPop>
	</view>
</template>
<script>
	import {
		mapActions
	} from 'vuex'
	export default {
		data() {
			return {
				couponShow3: false,
				coupopShow: false,
				gouChoice: false,
				timeData: {},
				couponIndex: -1,
				countDown: false,
				couponInfo: {}, //优惠券信息
				showOrigin: false,
				loadingShow: false,
				shows: 2,
				showpayment: 2,
				checkValue: [],
				checkVal: true,
				loadingShow: false,
				shows: 0,
				payRadio: 1,
				goodList: [],
				goodsId: '',
				payPrice: '',
			}
		},
		onLoad(option) {
			this.getGoods()
			uni.setStorageSync('guideIsOver', true)
			this.couponInfo = uni.getStorageSync('config')['client.coupon.tips']
		},
		mounted() {
			// #ifdef APP
			if (uni.getStorageSync('config')['client.coupon.tips']?.couponId > 0) {
				setTimeout(() => {
					this.coupopShow = true
				}, 1500)
				this.checkValue = ['']
			}
			// #endif
			
		},
		methods: {
			// 倒计时方法
			timeChange(e) {
				this.timeData = e
			},
			// 优惠券倒计时展示并关闭弹窗
			openCoupon() {
				this.countDown = false
				this.couponShow3 = true
				this.coupopShow = false
			},
			// 
			editOriginPrice() {
				this.countDown = true
				this.showOrigin = true
			},
			// 优惠勾选框
			couponChange(e) {
				this.checkValue = e
				if (this.shows != this.couponIndex) {
					uni.showToast({
						title: '优惠券仅终身会员可用',
						icon: 'none'
					})
				}
			},
			// 优惠勾选框
			checkboxChange(e) {
				if (e.length) {
					this.checkVal = true
				} else {
					this.checkVal = false
				}

			},
			// 商品切换
			change(e) {
				this.shows = e
				if (this.shows == this.couponIndex) {
					this.checkValue = ['']
				} else {
					this.checkValue = []
				}
			},
			// 协议框
			checkboxChange(e) {
				console.log(e);
				if (e.length) {
					this.checkValue = true
				} else {
					this.checkValue = false
				}
			},
			// 退出引导页
			to() {
				// this.$api.userEvent({
				// 	type: 'click',
				// 	key: 'guide.next.vipQuit.click',
				// 	value: "guide.vipQuit",
				// 	extra: '退出引导页'
				// }).then(res => {
				// 	console.log(res);
				// })
				this.toHome()
			},
			// 点击开通会员
			gonext() {
				if (this.loadingShow) return false
				// #ifdef MP-WEIXIN
				wx.reportEvent("guide_pay_click", {})
				// #endif

				this.$api.userEvent({
					type: 'click',
					key: 'guide.next.payButton.click',
					value: "payButton",
					extra: '点击开通会员'
				}).then(res => {
					console.log(res);
				})
				let that = this
				this.loadingShow = true
				// #ifdef APP || APP-PLUS
				plus.statistic.eventTrig('guide_pay_click', '点击开通会员')
				this.applyPayInit()
				// #endif
				// #ifdef MP-WEIXIN
				this.wxmpPay()
				// #endif

			},
			// 微信小程序支付
			wxmpPay() {
				console.log(this.goodList[this.shows])
				uni.showLoading()
				this.$api.createOrder({
					goodsId: this.goodList[this.shows].id,
					payPrice: this.goodList[this.shows].price,
					payType: 'wxapplet',
					source: "bootpage",
					couponId: (this.shows == this.couponIndex && this.checkValue.length) ? uni
						.getStorageSync(
							'config')['client.coupon.tips'].couponId : 0
				}).then(res => {
					uni.hideLoading()
					this.loadingShow = false
					if (res.data.code == 1019) {
						uni.switchTab({
							url: '/pages/index/home/home'
						})
						return
					}
					uni.requestPayment({
						"provider": "wxpay", //固定值为"wxpay"
						"package": res.data.data.package,
						"nonceStr": res.data.data.nonceStr, // 随机字符串
						"timeStamp": res.data.data.timeStamp, // 时间戳（单位：秒）
						"signType": res.data.data.signType,
						"paySign": res.data.data.paySign,
						success: function(res) {
							uni.showToast({
								title: '支付成功'
							})
							// #ifdef MP-WEIXIN
							wx.reportEvent("guide_pay_success", {})
							// #endif
							let timer = setTimeout(() => {
								uni.reLaunch({
									url: '/pages/index/login/login'
								})
								clearTimeout(timer)
							}, 1500)
						},
						fail: function(err) {
							console.log('支付失败:' + JSON.stringify(err));
						}
					});
				})
			},
			// 获取会员开通信息
			getGoods() {
				uni.showLoading()
				this.$api.getGoods().then(res => {
					console.log(res);
					uni.hideLoading()
					if (res.data.code == 0) {
						this.goodList = res.data.data
						if (this.couponInfo.couponId > 0) {
							this.couponIndex = this.goodList.findIndex(item => this.couponInfo.goodsIds == item.id)
						}
						let index = this.goodList.findIndex(item => item.checked)
						if (index >= 0) {
							this.shows = index
						}
					}
				})
			},
			/* 苹果支付部分 */

			// 校验支付环境
			applyPayInit() {
				uni.showLoading()
				let that = this
				uni.getProvider({
					service: "payment",
					success: res => {
						that.iapChannel = res.providers.find((channel) => channel.id === 'appleiap')
						if (!that.iapChannel) {
							that.loadingShow = false
							uni.hideLoading()
							return uni.showToast({
								title: '苹果支付失败',
								icon: "none"
							})
						}
						that.compareAppleProduce()
					},
					fail() {
						that.loadingShow = false
					},
				})
			},
			//校验苹果产品可以支付
			compareAppleProduce() {
				let that = this
				let appleId
				if ((this.shows == this.couponIndex && this.checkValue.length)) {
					appleId = this.goodList[this.shows].appleSpecialId
				} else {
					appleId = this.goodList[this.shows].appleProductId
				}
				that.iapChannel.requestOrder([appleId], (event) => {
					that.applePay(appleId)
				}, (err) => {
					this.loadingShow = false
					uni.hideLoading()
					uni.showToast({
						title: err.message + ',' + appleId,
						icon: 'none'
					})
				})
			},
			//苹果支付
			applePay(productId, outTradeNo) {
				let that = this
				uni.requestPayment({
					provider: 'appleiap',
					orderInfo: {
						productid: productId
					},
					success(res) {
						if (res.transactionReceipt) {
							that.$api.applePay({
								source: 'bootpage',
								receipt: res.transactionReceipt,
								environment: that.$store.state.iosEnvir
							}).then(result => {
								console.log(result)
								if (result.data.code == 0) {
									plus.statistic.eventTrig('guide_pay_click', {
										goodsId: that.goodList[that.shows].id
									})
									this.$api.userEvent({
										type: 'click',
										key: 'guide.next.payButton.click',
										value: "payButton",
										extra: that.goodList[that.shows].id
									}).then(res => {
										console.log(res);
									})
									uni.showToast({
										title: '支付成功',
										icon: 'none'
									})
									let timer = setTimeout(() => {
										// #ifdef MP
										uni.reLaunch({
											url: '/pages/index/login/login'
										})
										// #endif
										// #ifdef APP
										uni.reLaunch({
											url: '/packageA/pages/login/login'
										})
										// #endif
										clearTimeout(timer)
									}, 1000)
								}
							})
						} else {
							uni.showToast({
								title: "支付失败",
								icon: 'none'
							})
						}
					},
					fail(e) {
						//自定义提示，可以忽略
						uni.showToast({
							title: "支付已取消",
							icon: 'none'
						})
					},
					complete() {
						//给支付按钮解锁
						that.loadingShow = false
						uni.hideLoading()
					}
				})
			}

		},
	}
</script>
<script module="test" lang="renderjs">
	export default {
		mounted() {
			// ...
			// this.initPag()
		},
		methods: {
			// pag文件(支持本地相对路径)， canvas 的id名，播放次数
			async initPag(num = 0) {
				// 实例化 PAG
				const PAG = await window.libpag.PAGInit()
				// 获取 PAG 素材数据
				// https://pag.art/file/like.pag
				const buffer = await fetch('_www/static/pag/top-banner1.pag').then((response) => {
					return response.arrayBuffer()
				})
				// 加载 PAG 素材为 PAGFile 对象
				const pagFile = await PAG.PAGFile.load(buffer)
				// 将画布尺寸设置为 PAGFile的尺寸
				const canvas = document.getElementById('pag')
				canvas.width = pagFile.width()
				canvas.height = pagFile.height()
				// 实例化 PAGView 对象
				const pagView = await PAG.PAGView.init(pagFile, canvas)
				// 循环播放
				pagView.setRepeatCount(num)
				await pagView.play()
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'guide_6.scss';
</style>
<style>
	page {
		background-color: #18171D;
	}
</style>